package com.woogie.serv.async;

import com.woogie.serv.constants.Numbers;
import com.woogie.serv.constants.Strings;
import com.woogie.serv.pojo.Register;
import com.woogie.serv.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class SendDataThread extends Thread {
	
	String data;
	Socket socket;
	int port;
	boolean wait;
	
	SendDataThread(String data, int port, boolean wait){
		this.data = data;
		this.port = port;
		this.wait = wait;
	}

	@Override
	public void run() {
		try {
			socket = new Socket(Strings.SERVER_URL, port);
			
			DataInputStream dis = new DataInputStream(socket.getInputStream());
	    	DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); 
	    	
			dos.writeUTF(data);
			dos.flush();
			
			if (wait){
				String mess = readResponse(dis, data, port);
				
				String[] option = mess.split(Strings.SEPERATOR1);
				
				if (option[0].equalsIgnoreCase("Message"))
				{
					String[] option2 = option[1].split(Strings.SEPERATOR2);
					new SendMessage(option2[0], option2[1]).send();
					socket.close();
				}
				else if (option[0].equalsIgnoreCase("Registered"))
				{
					Register.save();
				}
			}
			else
				socket.close();
			
		} catch (Exception e) {
			e.printStackTrace();
			Log.log(e.getMessage());
			new DataFromServer().execute();
		} 
		finally{
			if (port != Numbers.CONNECTION_PORT_ALIVE){
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public String readResponse(DataInputStream dis, String data, int port) throws IOException{
		FutureTaskThread thread = new FutureTaskThread(data, port, wait);
		thread.start();
		String $return = dis.readUTF();
		thread.received = true;
		
		return $return;
	}
	
	public Socket getSocket(){
		return socket;
	}
}

class FutureTaskThread extends Thread{
	public boolean received = false;
	String data;
	int port;
	boolean wait;
	
	public FutureTaskThread(String data, int port, boolean wait){
		this.data = data;
		this.port = port;
		this.wait= wait;
	}
	
	@Override
	public void run() {
		try {
			if (port == Numbers.CONNECTION_PORT)
				Thread.sleep(2*60*1000);
			if (port == Numbers.CONNECTION_PORT_ALIVE)
				Thread.sleep(60*60*1000);
			if(!received){
				new SendDataThread(data, port, wait).start();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
